package al.xc.generator;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.io.*;
import java.nio.file.Paths;

public class GeneratorCode {

    private static String packageName = "al.xc.datasource";
    private static String outDir = "/data/develop/idea/new/live/tmp/";
    private static String entity = "model";
    private static String mapper = "mapper";
    private static String service = "service";
    private static String impl = "service.impl";
    private static String controller = "controller";
    private static String xml = "resources.mapper";

    public static String entityDst = "E:/SVN/奇千live/datasource/src/main/java/al/xc/datasource/";
    public static String mapperDst = "E:/SVN/奇千live/datasource/src/main/java/al/xc/datasource/";
    public static String xmlDst = "E:/SVN/奇千live/datasource/src/main/";

    // 0 不生成 1 生成不覆盖 2 覆盖
    private static int makeEntityFlag = 2;
    private static int makeControllerFlag = 0;
    private static int makeServiceFlag = 0;
    private static int makeServiceImplFlag = 0;
    private static int makeMapperFlag = 1;
    private static int makeXmlFlag = 1;

    private static String entityVM = "";
    private static String controllerVM = "";
    private static String serviceVM = "";
    private static String serviceImplVM = "";
    private static String mapperVM = "";
    private static String xmlVM = "";

    private static String url = "jdbc:mysql://47.103.192.191:3306/QuickSecond?allowMultiQueries=true&useAffectedRows=true&useUnicode=true&&characterEncoding=UTF-8&useSSL=false&serverTimeZone=GMT+8";
    private static String name = "sa";
    private static String password = "qiqian#888";
    private static String driver = "com.mysql.cj.jdbc.Driver";

    private static String [] baseDir = {entity, mapper, service, impl, controller};

    public static void test(String[] args) {
        boolean serviceNameStartWithI = true;
        generateByTables(serviceNameStartWithI, packageName,
                url, name, password, driver,"User_Info");
    }

    private static void generateByTables(boolean serviceNameStartWithI,
                                         String packageName,
                                         String url,
                                         String name,
                                         String password,
                                         String driverName,
                                         String... tableNames) {

        GlobalConfig config = new GlobalConfig();
        String dbUrl = url;
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL)
                .setUrl(dbUrl)
                .setUsername(name)
                .setPassword(password)
                .setDriverName(driverName);
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig
                .setCapitalMode(false)
                .setEntityLombokModel(true)
                .setRestControllerStyle(true)
                .setNaming(NamingStrategy.underline_to_camel)
                //修改替换成你需要的表名，多个表名传数组
                .setInclude(tableNames);
        config.setActiveRecord(true)
                .setAuthor("ZYY")
                .setOutputDir(outDir)
                .setBaseResultMap(true)
                .setBaseColumnList(true)
                .setFileOverride(true)
                .setEnableCache(false)
                // XML ResultMap
                .setBaseResultMap(true)
                // XML columList;
                .setBaseColumnList(true);
        if (!serviceNameStartWithI) {
            config.setServiceName("%sService");
        }

        PackageConfig pcf = initPackage();

        TemplateConfig tc = initTemplateConfig(packageName);
        if (new File(outDir).exists()) {
            new File(outDir).delete();
            new File(outDir).mkdir();
        }
        new AutoGenerator().setGlobalConfig(config)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(pcf)
                .setTemplate(tc)
                .execute();

        copyDst();
    }

    /**
     * 根据自己的需要，修改哪些包下面的 要覆盖还是不覆盖
     * @param packageName
     */
    private static TemplateConfig initTemplateConfig(String packageName) {
        TemplateConfig tc = new TemplateConfig();
        initVM(tc);
        return tc;
    }

    private static void initVM(TemplateConfig tc) {
        if(stringIsNotNull(entityVM)) {
            tc.setEntity(entityVM);
        }
        if(stringIsNotNull(mapperVM)) {
            tc.setMapper(mapperVM);
        }
        if(stringIsNotNull(serviceImplVM)) {
            tc.setServiceImpl(serviceImplVM);
        }
        if(stringIsNotNull(serviceVM)) {
            tc.setService(serviceVM);
        }
        if(stringIsNotNull(xmlVM)) {
            tc.setXml(xmlVM);
        }
        if(stringIsNotNull(controllerVM)) {
            tc.setController(controllerVM);
        }
    }

    /**
     * 简单判断字符串是不是为空
     * @param s
     * @return
     */
    private static boolean stringIsNotNull(String s) {
        if(null != s && !s.equals("") && s.length() > 0 && s.trim().length() > 0) {
            return true;
        }
        return false;
  }

    /**
     * 初始化包目录配置
     * @return
     */
    private static PackageConfig initPackage() {
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent(packageName);
        packageConfig.setService(service);
        packageConfig.setServiceImpl(impl);
        packageConfig.setController(controller);
        packageConfig.setEntity(entity);
        packageConfig.setXml(xml);
        return packageConfig;
    }

    private static void copyDst() {
        if (0 == makeEntityFlag || null == entityDst) {
            return;
        }
        copy(outDir + packageName.replace(".", "/") + "/" + entity.replace(".", "/"), entityDst + entity.replace(".", "/"), (2 == makeEntityFlag));
        copy(outDir + packageName.replace(".", "/") + "/" + mapper.replace(".", "/"), mapperDst + mapper.replace(".", "/"), (2 == makeMapperFlag));
        copy(outDir + packageName.replace(".", "/") + "/" + xml.replace(".", "/"), xmlDst + xml.replace(".", "/"), (2 == makeXmlFlag));
    }

    private static void copy(String srcPath, String dstPath, boolean isOver) {
        File srcFile = new File(srcPath);
        if (!new File(dstPath).exists()) {
            new File(dstPath).mkdir();
        }
        String[] fileList = srcFile.list();
        for (int i = 0; i < fileList.length; ++i) {
            String filePath = srcPath + srcFile.separator + fileList[i];
            if ((new File(filePath)).isDirectory()) {
                continue;
            }
            if (new File(filePath).isFile()) {
                try {
                    copyFile(filePath, dstPath + srcFile.separator + fileList[i], isOver);
                } catch (Exception ex) {}
            }
        }
    }

    private static void copyFile(String srcPath, String dstPath, boolean isOver) throws IOException {
        File dstFile = new File(dstPath);
        if (!isOver && dstFile.exists()) {
            return;
        }
        if (dstFile.exists()) {
            dstFile.createNewFile();
        }
        File srcFile = new File(srcPath);
        FileInputStream in = new FileInputStream(srcFile);
        FileOutputStream out = new FileOutputStream(dstFile);
        byte[] buffer = new byte[32 * 1024];
        int len = 0;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        in.close();
        out.close();
    }
}
